﻿using ELearning.BLL;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Http;
using ELearning.Common.CommonStr;
using ELearning.Models.ViewModel.Cls;

namespace ELearning.API.Controllers.AdminControllers
{
    /// <summary>
    /// 班级信息管理
    /// </summary>
    public class ClassController : BaseApiController
    {
        EClassService classService = new EClassService();
        RClassUserService classUserService = new RClassUserService();
        UserController userController = new UserController();
        OrderController orderController = new OrderController();
        EBuyRecordService orderService = new EBuyRecordService();
        RClassProductService clsProService = new RClassProductService();
        private ESysUserService userService = new ESysUserService();

        #region Base信息

        /// <summary>
        /// 获取所有班级信息-base
        /// </summary>
        /// <returns></returns>
        public List<EClass> GetClassListBase()
        {
            #region 组合Expression
            Expression<Func<EClass, bool>> explist = null;
            explist = u => u.IsDelete == false;
            #endregion
            return classService.FindList(explist, "CreateTime", true).ToList();
        }
        #endregion

        #region 班级信息

        /// <summary>
        /// 获取所有班级信息
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/getClassList")]
        [HttpGet]
        public object GetClassList()
        {
            List<ClsViewModel> clss = new List<ClsViewModel>();
            ClsViewModel cls = null;
            var clsList = GetClassListBase();

            Expression<Func<RClassUser, bool>> explist = null;

            foreach (var c in clsList)
            {
                explist = u => u.ClassID == c.ClassID;
                var rc = classUserService.FindList(explist).ToList();

                cls = new ClsViewModel();
                cls.ClassID = c.ClassID;
                cls.ClassName = c.ClassName;
                cls.ClassNum = rc.Count;
                cls.ClassType = c.ClassType;
                cls.Creater = c.Creater;
                cls.CreateTime = c.CreateTime;
                cls.IsDelete = c.IsDelete;
                cls.Modifyer = c.Modifyer;
                cls.ModifyTime = c.ModifyTime;
                cls.OrgCode = c.OrgCode;
                cls.Remark = c.Remark;
                cls.Status = c.Status;
                clss.Add(cls);
            }
            var json = new { classList = clss };
            return ServiceResponse<object>.SuccessResponse(json);
        }

        /// <summary>
        /// 获取搜素班级信息
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/searchClassList")]
        [HttpGet]
        public object SearchClassList(String ClassName, String ClassType, String Status)
        {
            #region 组合Expression
            Expression<Func<EClass, bool>> explist = null;
            explist = u => u.IsDelete == false;
            if (!string.IsNullOrWhiteSpace(ClassName))
            {
                explist = LinqExpression.And(explist, u => u.ClassName.Contains(ClassName));
            }
            if (!string.IsNullOrWhiteSpace(ClassType))
            {
                var classType = int.Parse(ClassType);
                explist = LinqExpression.And(explist, u => u.ClassType == classType);
            }
            if (!string.IsNullOrWhiteSpace(Status))
            {
                var status = bool.Parse(Status);
                explist = LinqExpression.And(explist, u => u.Status == status);
            }
            explist = LinqExpression.And(explist, u => u.OrgCode == CurrentUserModel.OrgCode);
            #endregion

            List<ClsViewModel> clss = new List<ClsViewModel>();
            ClsViewModel cls = null;
            var clsList = classService.FindList(explist);

            Expression<Func<RClassUser, bool>> explist1 = null;

            foreach (var c in clsList)
            {
                explist1 = u => u.ClassID == c.ClassID;
                var rc = classUserService.FindList(explist1).ToList();

                cls = new ClsViewModel();
                cls.ClassID = c.ClassID;
                cls.ClassName = c.ClassName;
                cls.ClassNum = rc.Count;
                cls.ClassType = c.ClassType;
                cls.Creater = c.Creater;
                cls.CreateTime = c.CreateTime;
                cls.IsDelete = c.IsDelete;
                cls.Modifyer = c.Modifyer;
                cls.ModifyTime = c.ModifyTime;
                cls.OrgCode = c.OrgCode;
                cls.Remark = c.Remark;
                cls.Status = c.Status;
                clss.Add(cls);
            }
            var json = new { classList = clss };

            return ServiceResponse<object>.SuccessResponse(json);
        }

        /// <summary>
        /// 添加班级
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/insertClassInfo")]
        [HttpPost]
        public object InsertClassInfo(EClass cls)
        {
            cls.ClassID = Guid.NewGuid();
            cls.OrgCode = CurrentUserModel.OrgCode;
            cls.CreateTime = DateTime.Now;
            cls.ModifyTime = DateTime.Now;
            var myList = classService.Add(cls);

            if (myList != null) return ServiceResponse<object>.SuccessResponse("添加班级成功");
            else return ServiceResponse<object>.ErrorResponse("添加班级失败");
        }

        /// <summary>
        /// 更新班级
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/updateClassInfo")]
        [HttpPost]
        public object UpdateClassInfo(EClass cls)
        {
            cls.ModifyTime = DateTime.Now;
            var myList = classService.Update(cls);

            if (myList) return ServiceResponse<object>.SuccessResponse("更新班级成功");
            else return ServiceResponse<object>.ErrorResponse("更新班级失败");
        }

        /// <summary>
        /// 删除班级
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/deleteClass")]
        [HttpPost]
        public object DeleteClass(String ClassID)
        {
            var classid = Guid.Parse(ClassID);
            #region 组合Expression
            Expression<Func<EClass, bool>> explist = null;
            explist = u => u.ClassID == classid;
            #endregion
            var cls = classService.Find(explist);
            cls.IsDelete = true;
            var myList = classService.Update(cls);

            if (myList) return ServiceResponse<object>.SuccessResponse("删除班级成功");
            else return ServiceResponse<object>.ErrorResponse("删除班级失败");
        }

        #endregion

        #region 班级添加用户

        /// <summary>
        /// 获取当前班级与用户信息
        /// </summary>
        /// <param name="classID"></param>
        /// <param name="loginName"></param>
        /// <param name="userName"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        [Route("api/cls/searchClassUserList")]
        [HttpGet]
        public object SearchClassUserList(string classID, string loginName, string userName, string userType)
        {
            var users = classUserService.GetClassUserList(classID, loginName, userName, userType);

            return ServiceResponse<object>.SuccessResponse(users);
        }

        /// <summary>
        /// 获取当前班级与用户信息-非当前班级的用户
        /// </summary>
        /// <param name="classID"></param>
        /// <param name="loginName"></param>
        /// <param name="userName"></param>
        /// <param name="orgCode"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        [Route("api/cls/searchUserOtherList")]
        [HttpGet]
        public object SearchUserOtherList(string classID, string loginName, string userName, string orgCode, string userType)
        {
            if (string.IsNullOrWhiteSpace(orgCode)) orgCode = CurrentUserModel.OrgCode;
            var users = classUserService.GetUserOtherList(classID, loginName, userName, orgCode, userType);

            return ServiceResponse<object>.SuccessResponse(users);
        }

        /// <summary>
        /// 班级添加学生
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/insertClassUser")]
        [HttpPost]
        public object InsertClassUser(string loginName, string classID)
        {
            RClassUser classUser = new RClassUser();
            classUser = new RClassUser();
            classUser.LoginName = loginName;
            classUser.ID = Guid.NewGuid();
            classUser.CreateTime = DateTime.Now;
            classUser.ModifyTime = DateTime.Now;
            classUser.ClassID = Guid.Parse(classID);
            classUser.Creater = CurrentUserModel.LoginName;

            var r = classUserService.Add(classUser);
            if (r != null) return ServiceResponse<object>.SuccessResponse("分配用户成功");
            else return ServiceResponse<object>.ErrorResponse("分配用户失败");
        }

        /// <summary>
        /// 班级添加学生-批量
        /// </summary>
        /// <param name="users">用户列表</param>
        /// <param name="classID">班级ID</param>
        /// <returns></returns>
        [Route("api/cls/insertClassUsers")]
        [HttpPost]
        public object InsertClassUser(List<ESysUser> users, string classID)
        {
            var cid = Guid.Parse(classID);
            List<RClassUser> classUsers = new List<RClassUser>();
            RClassUser classUser = null;
            foreach (var u in users)
            {
                classUser = new RClassUser();
                classUser.LoginName = u.LoginName;
                classUser.ID = Guid.NewGuid();
                classUser.CreateTime = DateTime.Now;
                classUser.ModifyTime = DateTime.Now;
                classUser.UserID = u.UserID;
                classUser.UserType = u.UserType;
                classUser.ClassID = cid;
                classUser.Creater = CurrentUserModel.LoginName;
                classUsers.Add(classUser);
            }

            var r = classUserService.Adds(classUsers);
            var d = classUserService.DeleteRepeated();
            if (r == users.Count) return ServiceResponse<object>.SuccessResponse("分配用户成功");
            else if (r > 0) return ServiceResponse<object>.SuccessResponse("分配用户成功" + r + "人" + "；失败" + (users.Count - r) + "人");
            else return ServiceResponse<object>.ErrorResponse("分配用户失败");
        }

        /// <summary>
        /// 移除班级中用户
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/deleteClassUser")]
        [HttpPost]
        public object DeleteClassUser(List<ESysUser> users, string classID)
        {
            var loginNames = users.Select(u => u.LoginName).ToList();
            var arr = string.Join(",", loginNames);
            arr = arr.Replace(",", "','");
            arr = "'" + arr + "'";

            var r = classUserService.DeleteClassUser(classID, arr);

            if (r == users.Count) return ServiceResponse<object>.SuccessResponse("移除用户成功");
            else if (r > 0) return ServiceResponse<object>.SuccessResponse("移除用户成功" + r + "人" + "；失败" + (users.Count - r) + "人");
            else return ServiceResponse<object>.ErrorResponse("移除用户失败");
        }

        #endregion

        #region 班级分配产品

        /// <summary>
        /// 获取当前已分配的产品信息
        /// </summary>
        /// <param name="classID"></param>
        /// <param name="productName"></param>
        /// <returns></returns>
        [Route("api/cls/searchProductCls")]
        [HttpGet]
        public object SearchProductCls(string classID, string productName)
        {
            var org = CurrentUserModel.OrgCode;

            var pro = classUserService.GetProductCls(org, classID, productName);

            return ServiceResponse<object>.SuccessResponse(pro);
        }

        /// <summary>
        /// 获取当前产品信息-未分配
        /// </summary>
        /// <param name="classID"></param>
        /// <param name="productName"></param>
        /// <returns></returns>
        [Route("api/cls/searchProductClsOther")]
        [HttpGet]
        public object SearchProductClsOther(string classID, string productName)
        {
            var orgCode = CurrentUserModel.OrgCode;
            var clss = classUserService.GetProductClsOther(orgCode, classID, productName);

            return ServiceResponse<object>.SuccessResponse(clss);
        }

        /// <summary>
        /// 为班级分配产品-批量
        /// </summary>
        /// <param name="pros"></param>
        /// <param name="classID"></param>
        /// <returns></returns>
        [Route("api/cls/insertProductCls")]
        [HttpPost]
        public object InsertProductCls(List<OrderViewModel> pros, string classID)
        {
            var clsid = Guid.Parse(classID);
            List<RClassProduct> clspro = new List<RClassProduct>();
            RClassProduct clsp = null;
            foreach (var u in pros)
            {
                clsp = new RClassProduct();
                clsp.ID = Guid.NewGuid();
                clsp.ClassID = clsid;
                clsp.ProductID = u.ID;
                clsp.OrgCode = CurrentUserModel.OrgCode;
                clsp.Creater = CurrentUserModel.LoginName;
                clsp.CreateTime = DateTime.Now;
                clsp.Modifyer = CurrentUserModel.LoginName;
                clsp.ModifyTime = DateTime.Now;

                clspro.Add(clsp);
            }

            var r = clsProService.Adds(clspro);
            if (r == pros.Count) return ServiceResponse<object>.SuccessResponse("分配产品成功");
            else if (r > 0) return ServiceResponse<object>.SuccessResponse("分配产品成功" + r + "个" + "；失败" + (pros.Count - r) + "个");
            else return ServiceResponse<object>.ErrorResponse("分配产品失败");
        }

        /// <summary>
        /// 移除已分配的产品
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/deleteProductCls")]
        [HttpPost]
        public object DeleteProductCls(List<OrderViewModel> pros, string classID)
        {
            var pid = pros.Select(u => u.ID).ToList();
            var arr = string.Join(",", pid);
            arr = arr.Replace(",", "','");

            var r = classUserService.DeleteClassProduct(classID, arr);

            if (r == pros.Count) return ServiceResponse<object>.SuccessResponse("移除产品成功");
            else if (r > 0) return ServiceResponse<object>.SuccessResponse("移除产品成功" + r + "个" + "；失败" + (pros.Count - r) + "个");
            else return ServiceResponse<object>.ErrorResponse("移除产品失败");
        }

        #endregion

        #region 获取教师下的班级

        /// <summary>
        /// 获取教师下的班级
        /// </summary>
        /// <returns></returns>
        [Route("api/cls/getMyClass")]
        [HttpGet]
        public object GetMyClass()
        {
            var tea = CurrentUserModel.LoginName;

            var pro = classUserService.GetMyClass(tea);

            return ServiceResponse<object>.SuccessResponse(pro);
        }

        #endregion

        /// <summary>
        /// 获取教师下的班级，转化ewmodel
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/cls/GetUserClass")]
        [AllowAnonymous]
        public ServiceResponse<UserClassViewModel> GetUserClass()
        {
            var tea = CurrentUserModel.LoginName;
            var pro = classUserService.GetMyClass(tea);
            var viewModel = new UserClassViewModel();
            foreach (var eClass in pro)
            {
                viewModel.ClsList.Add(new ClsItem
                {
                    ClassId = eClass.ClassID,
                    ClassName = eClass.ClassName
                });
            }

            return ServiceResponse<UserClassViewModel>.SuccessResponse(viewModel);
        }


        /// <summary>
        /// 获取班级下的学生
        /// </summary>
        /// <param name="clsIds">班级id</param>
        /// <returns></returns>
        [HttpGet, Route("api/cls/GetClassStudent")]
        [AllowAnonymous]
        public ServiceResponse<List<string>> GetClassStudent(string clsIds)
        {
            var users=new List<string>();
            if (!string.IsNullOrEmpty(clsIds))
            {
                var clsIdList = clsIds.Split(',').ToList();
                var clsGuids = new List<Guid>();
                foreach (var id in clsIdList)
                {
                    clsGuids.Add(Guid.Parse(id));
                }
                var userLoginNames = classUserService.FindList(r => r.UserType == UserType.UserTypeSTUDENT && clsGuids.Contains(r.ClassID)).Select(r => r.LoginName).Distinct().ToList();
                users = userService.FindList(u => !u.IsDelete && userLoginNames.Contains(u.LoginName)).Select(u => u.UserName).ToList();
            }
            
            return ServiceResponse<List<string>>.SuccessResponse(users);
        }
    }
}